<template>
  <div class="knowledge-management">
    <div class="page-header">
      <h1 class="page-title">
        <Database :size="24" style="margin-right: 12px;" />
        知识库管理
      </h1>
      <p class="page-description">管理系统中的知识库内容和配置</p>
    </div>

    <div class="content-area">
      <a-row :gutter="16">
        <a-col :span="24">
          <a-card title="知识库列表" :bordered="false">
            <template #extra>
              <a-space>
                <a-button @click="handleRefresh" :loading="loading">
                  <RotateCcw :size="16" style="margin-right: 4px;" />
                  刷新
                </a-button>
                <a-button type="primary" @click="handleCreate">
                  <Plus :size="16" style="margin-right: 4px;" />
                  创建知识库
                </a-button>
              </a-space>
            </template>

            <a-table
              :columns="columns"
              :data-source="knowledgeList"
              :pagination="pagination"
              :loading="loading"
              row-key="id"
              @change="handleTableChange"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="getStatusColor(record.status)">
                    {{ getStatusText(record.status) }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'fileSize'">
                  {{ formatSize(record.fileSize) }}
                </template>
                <template v-else-if="column.key === 'createdAt'">
                  {{ formatDate(record.createdAt) }}
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-space>
                    <a-button type="link" size="small" danger @click="handleDelete(record)">
                      删除
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 创建知识库弹窗 -->
    <CreateKnowledgeModal
      v-model:open="createModalVisible"
      @success="handleCreateSuccess"
    />

    <!-- 删除知识库弹窗 -->
    <DeleteKnowledgeModal
      v-model:open="deleteModalVisible"
      :knowledge-base="selectedKnowledge"
      @success="handleDeleteSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Database, Plus, RotateCcw } from 'lucide-vue-next'
import { message } from 'ant-design-vue'
import { Codewin } from '@/api/generated/Codewin'
import type { KnowledgeBaseListVO } from '@/api/generated/data-contracts'
import { useAuthStore } from '@/stores/modules/auth'
import { useResourceStore } from '@/stores'
import CreateKnowledgeModal from '@/components/KnowledgeManager/CreateKnowledgeModal.vue'
import DeleteKnowledgeModal from '@/components/KnowledgeManager/DeleteKnowledgeModal.vue'

// Store
const authStore = useAuthStore()
const resourceStore = useResourceStore()

// API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'https://www.codewin.top'
})

// 响应式数据
const loading = ref(false)
const knowledgeList = ref<KnowledgeBaseListVO[]>([])
const createModalVisible = ref(false)
const deleteModalVisible = ref(false)
const selectedKnowledge = ref<KnowledgeBaseListVO | null>(null)

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '知识库名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
  },
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
  },
  {
    title: '文件大小',
    dataIndex: 'fileSize',
    key: 'fileSize',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
  },
]

// 获取知识库列表
const fetchKnowledgeList = async (pageNo = 1, pageSize = 10) => {
  loading.value = true
  try {
    // 设置Authorization header
    const headers: Record<string, string> = {}
    if (authStore.token) {
      headers['Authorization'] = `Bearer ${authStore.token}`
    }

    const response = await api.getKnowledgeBaseList(
      {
        pageNo,
        pageSize
      },
      {
        headers
      }
    )

    if (response.data?.code === 0 && response.data.data) {
      knowledgeList.value = response.data.data.list || []
      pagination.value.total = response.data.data.total || 0
      pagination.value.current = pageNo
      pagination.value.pageSize = pageSize
      console.log('知识库列表加载成功:', knowledgeList.value.length, '个知识库')
    } else {
      console.error('获取知识库列表失败:', response.data?.message)
      message.error('获取知识库列表失败')
    }
  } catch (error) {
    console.error('获取知识库列表失败:', error)
    message.error('获取知识库列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 获取状态颜色
const getStatusColor = (status: number) => {
  const colorMap: Record<number, string> = {
    0: 'processing', // 创建中
    1: 'success',    // 创建成功
    2: 'error',      // 创建失败
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status: number) => {
  const textMap: Record<number, string> = {
    0: '创建中',
    1: '正常',
    2: '创建失败',
  }
  return textMap[status] || '未知'
}

// 格式化文件大小
const formatSize = (bytes: number) => {
  if (!bytes || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  try {
    // 统一格式：去掉T字符，只保留到秒
    return dateString.replace('T', ' ').split('.')[0]
  } catch (error) {
    return dateString
  }
}

// 处理表格变化
const handleTableChange = (pag: any) => {
  fetchKnowledgeList(pag.current, pag.pageSize)
}

// 处理刷新
const handleRefresh = () => {
  fetchKnowledgeList(pagination.value.current, pagination.value.pageSize)
}

// 处理创建知识库
const handleCreate = () => {
  createModalVisible.value = true
}

// 处理创建成功
const handleCreateSuccess = () => {
  // 刷新列表
  fetchKnowledgeList(pagination.value.current, pagination.value.pageSize)
  // 同步到resource store
  resourceStore.fetchKnowledgeBases(true)
}

// 处理查看
const handleView = (record: KnowledgeBaseListVO) => {
  message.info(`查看知识库: ${record.name}`)
}

// 处理编辑
const handleEdit = (record: KnowledgeBaseListVO) => {
  message.info(`编辑知识库: ${record.name}`)
}

// 处理删除
const handleDelete = (record: KnowledgeBaseListVO) => {
  selectedKnowledge.value = record
  deleteModalVisible.value = true
}

// 处理删除成功
const handleDeleteSuccess = () => {
  // 刷新列表
  fetchKnowledgeList(pagination.value.current, pagination.value.pageSize)
  // 同步到resource store
  resourceStore.fetchKnowledgeBases(true)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchKnowledgeList()
})
</script>

<style scoped>
.knowledge-management {
  height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  display: flex;
  align-items: center;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.content-area {
  height: calc(100% - 100px);
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}
</style>
